<template>
    <view style="display: flex; flex-direction: column; height: 100vh">
		<xmInfo
		    :projectno="itemContent.projectno"
		    :projectname="itemContent.projectname"
		  ></xmInfo>
		  <view style="flex: 1;  overflow: scroll;padding: 10px;">
			  <view v-if="list.length" v-for="(item,index) in list" :key="index"  style="width: 100%; display: flex;align-items: center;justify-content: space-between; margin-bottom: 10px;background-color: #fff;padding: 10px;">
			  	<view style="display: flex;flex: 1;">
			  		<u-icon :name="fileUrl(item.fileExtension)" :size="80"></u-icon>
			  		<view  style="margin: 0 10px;width: 470rpx;overflow: hidden;">
			  			<view  class="text-lg"style="
												width: 100%;
										display: -webkit-box;
										-webkit-box-orient: vertical; 
										-webkit-line-clamp: 1; 
										overflow: hidden; 
										text-overflow: ellipsis;"> 
						{{item.fileName}}
						</view>
			  			<view style="color: #aaa;margin-top: 5px;">
							<view >类型：{{item.fileType || ''}}</view>
							<view style="display: flex;justify-content: space-between;">
							 <text>提交：{{item.pmProjFiles.createDate.slice(0, 10)}}</text>	
							<text style="color: #aaa;margin-left:10px;"> {{item.fileUpload.fileEntity.fileSizeFormat || ''}}</text>
							</view>
							<view >审核：{{item.pmProjFiles.auditDate?item.pmProjFiles.auditDate.slice(0, 10):''}}</view>
			  			</view>
			  		</view>
			  	</view>
				
				<view style="width: 50px;display: flex;justify-content: space-between;flex-direction: column;">
					<js-select v-model="item.pmProjFiles.status" dict-type="zf_file_status" placeholder=" " :disabled="true"></js-select>
					
					<view @click="click(item)" style="width: 50px;color: #3E97B0;text-align: right;margin-top: 20px;">
						下载
					</view>
				
				</view>
				
			  </view>
			<u-empty v-if="!list.length"></u-empty>
		</view>
		<js-lang v-if="title" :title="title"></js-lang>
    </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
  export default{
  components: {xmInfo },
    data(){
        return{
			title:'',
			triggered: false,
			loadStatus: 'loadmore',
			query: {
				// pageNo: 1,
				// pageSize: 20,
			},
			itemContent:{},
            imgList: ["http://192.168.1.49:8080/app/static/image/zfgs/zfgs1.jpg","http://192.168.1.49:8080/app/static/image/zfgs/zfgs2.jpg"],
            list:[]
        }
    },
	 async onShow() {
		// this.query.pageNo = 1;
		// this.loadList();
		this.$u.api.zfgs.pmProjFilesListFilesByType(this.query).then(res => {
			this.list = res;
		})
	},
	onLoad(e) {
	  if (typeof e.item !== "undefined") {
	    try {
	      this.itemContent = JSON.parse(e.item);
		  this.title = this.itemContent.title
		  this.query.fileType = this.itemContent.id;
		  this.query.projectno = this.itemContent.projectno;
	    } catch (error) {
	      console.error("Failed to parse item:", error);
	    }
	  } else {
	    console.warn("Item is undefined.");
	  }
	},
	
    methods:{
		async refresherrefresh() {
			this.triggered = true
			this.query.pageNo = 1;
			await this.loadList()
			this.triggered = false
		},
		// 预览图片
		doPreviewImage(url) {
		  // const images = this.lists.map((item) => item.url || item.path);
		  uni.previewImage({
		    urls: [url],
		    current: url,
		    success: () => {
		      // this.$emit("on-preview", url, this.lists, this.index);
		    },
		    fail: () => {
		      uni.showToast({
		        title: "预览图片失败",
		        icon: "none",
		      });
		    },
		  });
		},
		async downloadAndOpenFile(serverUrl) {
		  
		  uni.downloadFile({
		    url: serverUrl,
		    success: function (res) {
		      var filePath = res.tempFilePath;
		      console.log(filePath, res,'filePath===');
		      uni.openDocument({
		        filePath: filePath,
		        showMenu: true,
		        success: function (res) {
		          console.log("打开文档成功");
		        },
		      });
		    },
		    fail: function (err) {
		      console.log(err);
		    },
		  });
		},
		extractUrl(url) {
			console.log(url)
			const regex = /^http\:\/\/[^\/]+\//;
			const match = url.match(regex);
			return match ? match[0] : null;
		},
		click(item){
			if(item.downType != '0'){
				this.$u.api.zfgs.pmAttachmentCheck({id:item.id,type:'1'}).then(res => {
					console.log(res);
					if(res.result == '200'){
						// let url = this.vuex_config.baseUrl + '/proj/attachment/pmAttachment/download?id=' + item.id+'&type=1'
						const hostUrl = this.extractUrl(this.vuex_config.baseUrl);
						this.downloadAndOpenFile(hostUrl + res.data)
					}else if(res.result == '203'){
						const hostUrl = this.extractUrl(this.vuex_config.baseUrl);
						const dataurl = hostUrl + res.data;
						console.log(dataurl,'dataurl')
					   	uni.setClipboardData({
							data: dataurl,
							success: ()=> {}
						});
						uni.showModal({
							title: '提示',
							content: '(大文件)链接已复制，请前往浏览器下载',
							showCancel: false,
							success: function(res) {}
						});
						// window.location.href = res.data
					}else{
						uni.showModal({
							title: '提示',
							content: res.message,
							showCancel: false,
							success: function(res) {}
						});
					}
				})
			}else{
				let url = ''
				if(item.fileUpload.fileUrl.startsWith('http')){
					url = item.fileUpload.fileUrl
				}else{
					url = this.vuex_config.baseUrl + item.fileUpload.fileUrl
				}
				
				if('.gif.bmp.jpeg.jpg.ico.png.tif.tiff'.includes(item.fileExtension)){
					
					this.doPreviewImage(url)
				}else{
					this.downloadAndOpenFile(url)
				}
			}
			
		},
		fileUrl(e){
			let src = e.toLowerCase()
			if('.gif.bmp.jpeg.jpg.ico.png.tif.tiff.image'.includes(src)){
				return '/static/image/file/png.png'
			}else if('.flv.swf.mkv.webm.mid.mov.mp3.mp4.m4v.mpc.mpeg.mpg.swf.wav.wma.wmv.avi.rm.rmi.rmvb.aiff.asf.ogg.ogv'.includes(src)){
				return '/static/image/file/mp4.png'
			}else if('.doc.docx'.includes(src)){
				return '/static/image/file/doc.png'
			}else if('.xls.xlsx.csv.excel'.includes(src)){
				return '/static/image/file/excel.png'
			}else if('.ppt.pptx'.includes(src)){
				return '/static/image/file/ppt.png'
			}else if('.pdf'.includes(src)){
				return '/static/image/file/pdf.png'
			}else if('.txt.xml.md'.includes(src)){
				return '/static/image/file/txt.png'
			}else if('.rar.zip.7z.tar.tgz.jar.gz.gzip.bz2.compression'.includes(src)){
				return '/static/image/file/rar.png'
			}else if('.dwg.cad'.includes(src)){
				return '/static/image/file/dwg.png'
			}else{
				return '/static/image/file/file.png'
			}
		},
		loadList(type) {
			this.$u.api.zfgs.pmProjFilesListFilesByType(this.query).then(res => {
				if (res.list.length < 20 || res.list.length == 0) {
					this.loadStatus = "nomore";
				}
				var list = res.list;
				if (type == "add") {
					for (var i = 0; i < list.length; i++) {
						this.list.push(list[i])
					}
				} else {
					this.list = list;
				}
			})
		
		},
		loadMore() {
			this.loadStatus = "loading";
			setTimeout(() => {
				this.query.pageNo += 1;
				this.loadList("add");
			}, 100);
		},
		
        add(item){
            console.log(item,'item')
            if(item){
                uni.navigateTo({
                    url: '/pages/zfgs/proj/zg/pmRectification/form?id='+item.id
                })
            }else{
                uni.navigateTo({
                    url: '/pages/zfgs/proj/zg/pmRectification/form?projectno='+this.itemContent.projectno + '&name='+this.itemContent.projectname + "&id=''"
                })
            }
        },
        ViewImage(imageList,e) {
            // 阻止冒泡
            const url = imageList.map(item => item.url);
            e.stopPropagation();
            uni.previewImage({
                urls: url,
                current: e.currentTarget.dataset.url
            });
        },
    }
  }

</script>
<style lang="scss" scoped>
	/deep/ .u-progress.data-v-0d33af60 {
		display: none;
	}
	/deep/.u-input__input.data-v-460c1d26 {
	    text-align: right;
	}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot{
    background: #fff;
}
.cu-item{
  flex-wrap: wrap;
  padding: 15px !important;
}
.title{
    flex-shrink: 0;
}
.grid-square{
    margin-bottom: 0 !important;
}
::v-deep .u-input__input{
	text-align: right;
}
</style>